<template>
    <div>
        <m-header :hasTitle="true" title="选择收货地址" :hasBack="true" :goBack="toHome" textAlign="center" ref="header">
        	<slot name="zx">
        		<div id="add_address" style="padding-right: 0.8rem;width: 30%; text-align: right; position: relative; z-index: 5;" class="aui-pull-right text-del" @click.stop="goAddAddress">新增地址</div>
        	</slot>
        </m-header>
        <div id="perChoose">
            <div class="searcher">
                <div class="aui-searchbar-input aui-border-radius" style="background:#F5F5F5;">
                    <i class="icon njfont nj-sousuo"></i>
                    <input type="search" placeholder="请搜索地址" id="search-input" ref='searcher' v-model="keyword">
                    <div id="searchList"></div>
                    <div class="aui-searchbar-clear-btn">
                        <i class="aui-iconfont aui-icon-close"></i>
                    </div>
                </div>
            </div>
            <div id="allmap" style="display:none;">
            </div>
            <div class="location">
                <i class="icon njfont nj-dizhi" style="font-size:.9rem;"></i><span style="text-indent: .4rem;" class="deliveryAddress">送至：{{locationInfo ? locationInfo.address : ScopeOutInfo ? ScopeOutInfo.address : "定位中..."}}</span>
            </div>
            <div class="deliveryAdd">
                我的收货地址
            </div>
            <HomeChooseAddress ref="chooseAddress"></HomeChooseAddress>
            <div class="deliveryAdd">
                附近地址
            </div>
            <div class="assumeList" ref="assumeList">
                <ul ref="assumeListUL">
                    <li v-for="(item, index) of positionList" :key="index" @click="addPosition(item)">
                        <p v-if="item.inArea" style="color:black;opacity: .9;">{{item.name}}</p>
                        <p v-if="item.inArea" style="color:black;opacity: .9;">{{item.district}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity: .4;">{{item.name}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity: .4;">{{item.district}}</p>
                    </li>
                </ul>
            </div>
            <div class="vicinty">
                <ul>
                    <li v-for="(item, index) of locateSpot" :key="index" class="locateSpot">
                        <span @click="firstLocation(item)" class="firstLocation" style="display: inline-block;width: 70%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: left;">
                            {{item.address || item.formateAdd || '定位中...'}}</span>   
                        <span @click="relocate" class="relocate" style="color: #80B760;"><i class="icon njfont nj-dingwei1"></i>重新定位</span>
                    </li>
                    <li v-for="(item, index) of vicintyList" :key="index" @click="addLocation(item)" class="nearlySpot">
                        <p v-if="item.inArea" style="color:black;opacity:.7;" :class="index == 0 ? 'firstItem' : 'others'">{{item.name}}</p>
                        <p v-if="!item.inArea" style="color:black;opacity:.3;" :class="index == 0 ? 'firstItem' : 'others'">{{item.name}}</p>
                    </li>
                    <li @click="ToMap" class="moreLocation"><span>更多地址</span><img src="static/image/index-arrow.png" style="width: .5rem;transform: rotate(90deg);"></li>
                </ul>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex';
import {Toast} from "../../utils/toast";
import header from "../header";
import { showLoading ,hideLoading} from "../../utils/loading";
import HomeChooseAddress from '../../real-components/HomeChooseAddress';
export default {
    data () {
        return {
            location:"xxx酒店",
            shopList:"",
            storeList: [],
            clientHeight: 0,
            headerHeight: 0,
            searcherHeight: 0,
            positionList: [],   //联想列表
            locateSpot:[{address: '定位中...'}],      //定位点
            vicintyList: [],    //附近点列表
            polygonList:[],     //存储可配送区域
            searchCity:'',
            keyword:''
        }
    },
    components:{
        "m-header": header,
        HomeChooseAddress
    },
    computed:{
        ...mapGetters('qxz',{
            locationInfo: 'getLocation',
            ScopeOutInfo: 'getScopeOut'
        }),
        ...mapGetters('wxh',[
        	"login"
        ]),
    },
    mounted(){
        let searcher = this.$refs.searcher;
        this.$route.query.clue && searcher.focus();
        this.noExtra();
        this.getStoreList();
        this.initScript();
        this.clientHeight = document.querySelector("body").clientHeight;
        this.reset();
        //this.headerHeight = document.querySelector(".nav_root").style.height;
        //this.searcherHeight = document.querySelector(".searcher").style.height;
        //console.log(this.headerHeight,this.searcherHeight,document.querySelector(".nav_root"),document.querySelector(".searcher"));
    },
    methods:{
        ...mapActions( 'zx',{
			addAddressQuicker: "addAddressQuicker"
        }),
        ...mapMutations('zx',[
        	"setaddFlagMutation","setNowAddressMutation"
        ]),
        //前往添加地址
        goAddAddress(){
        	// console.log(this.login,'登录')
        	if(this.login){
        		var address = {
					address:null,
					city:null,
					defaultaddress:"1",
					label:"0",
					phone:"",
					positionlat:null,
					positionlng:null,
					province:null,
					receivername:"",
					region:null,
					result:"",
					sex:"0",
					houseNumber:''
				}
				this.setaddFlagMutation(true);
				this.setNowAddressMutation(address);
				this.$router.push({path:'addAddress',query:{toFrom:'chooseAddress'}});
        	}else{
        		this.$router.push({path:'login',query:{page:"chooseAddress"}});
        	}
        },
        //获取本地储存的当前位置
        getPos(){
            let Pos = JSON.parse(localStorage.getItem("currentPos"));
            return Pos;
        },
        //回到首页
        toHome(){
            this.$router.push('home');
        },
        //重置高度
        reset(){
            this.$nextTick(function () {
                let header = document.querySelector(".nav_root");
                document.querySelector("#perChoose").style.height = this.clientHeight - header.offsetHeight + 'px';
            })
        },
        noExtra(){
            if(localStorage.getItem('currentPos')){
                this.locateSpot = [];
                this.locateSpot.push(JSON.parse(localStorage.getItem('currentPos')));
            }
        },
        //获取门店列表
        getStoreList(){
            var url = window.api.base_host + "/baseStore/getRestStore";
            let that = this;
            var params = {
                enterpriseCode: window.api.enterpriseCode
            }
            var config = {
                url: url,
                methods: "GET",
                params
            }
            axios(config).then((res) => {
                if (res.data.returnCode == 1) {
                    that.storeList = res.data.data[0];
                    that.$store.dispatch('qxz/updateStoreList', res.data.data[0]);
                }
            })
        },
        //添加联想列表地址
        addPosition(item){
            if(item.inArea){
                let that = this;
                let obj = new Object();
                AMap.service('AMap.Geocoder',function(){//回调函数
                    //实例化Geocoder
                    let geocoder = new AMap.Geocoder({
                        // city: "010"//城市，默认：“全国”
                    });
                    //TODO: 使用geocoder 对象完成相关功能
                    var lnglatXY=[item.location.lng, item.location.lat];//地图上所标点的坐标
                    geocoder.getAddress(lnglatXY, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                        //获得了有效的地址信息:
                        //即，result.regeocode.formattedAddress
                            // console.log(result,"给小周");
                            obj.province = result.regeocode.addressComponent.province;
                            obj.city = result.regeocode.addressComponent.city || '市辖区';
                            obj.region = result.regeocode.addressComponent.district;
                            obj.address = result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber + result.regeocode.addressComponent.township;
                            obj.positionlng = item.location.lng;
                            obj.positionlat = item.location.lat;
                            obj.addressid = "-1";
                            // console.log(obj,"item");
                            that.$store.dispatch('qxz/updateLocation', obj);
                            localStorage.setItem("locateIn", JSON.stringify(obj));
                            localStorage.setItem("chooseAddressActiveIndex", null);
                        }else{
                        //获取地址失败
                        }
                    });
                })
                this.positionList = [];
                document.querySelector("#search-input").value = "";
            }else{
                Toast({
                    "message": "不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //添加附近地址
        addLocation(item){
            // console.log(item,"item");
            if(item.inArea){
                var obj = {
					province: item.pname,
					city: item.cityname,
					region: item.adname,
					address: item.address,
					positionlng: item.location.lng,
                    positionlat: item.location.lat,
                    addressid: "-1"
                }
                this.$store.dispatch('qxz/updateLocation', obj);
            }else{
                Toast({
                    "message": "不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //附近地址第一个
        firstLocation(item){
            if(item.inArea){
                var obj = {
					province: item.addressComponent.province,
					city: item.addressComponent.city,
					region: item.addressComponent.district,
					address: item.formattedAddress,
					positionlng: item.position.lng,
                    positionlat: item.position.lat,
                    addressid: "-1"
                }
                this.$store.dispatch('qxz/updateLocation', obj);
            }else{
                Toast({
                    "message": "不在配送范围内",
			        "duration": 1500,
					"type" : "fail"
                })
            }
        },
        //判断ios版本
        getIosVersion() {
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if (isAndroid) {
                //这个是安卓操作系统
                return false
            }
            if (isIOS) {
        　　　　//这个是ios操作系统
                var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                // ver = parseInt(ver[1], 10);
                var IosVersion = (ver[1] || '0') + (ver[2] || '0') + (ver[3] || '0');
                if(Number(IosVersion) < 935) {
                    return true
                }else {
                    return false
                }
            }
        },
        //初始化高德地图脚本
        initScript() {
            //判断如果有script就删掉
            let that = this;
			if (document.querySelector("#amap-box")){
				document.body.removeChild(document.querySelector("#amap-box"));
			}
			let amapBox = document.createElement("div");
			amapBox.setAttribute("id", "amap-box");
			// this.initMap();
			let script1 = document.createElement("script");
			script1.onload = () => {
				let script2 = document.createElement("script");
				script2.onload = () => {
                    function waitMap (){
                        if(AMap.Map){
                            that.initMap();
                        }else{
                            setTimeout(() => {
                                waitMap();
                            },300)
                        }
                    }
                    waitMap();
				}
				script2.src = "//webapi.amap.com/ui/1.0/main.js";
				amapBox.insertAdjacentElement("beforeend", script2);
			};
            // script1.src = `http://webapi.amap.com/maps?v=${this.getIosVersion() ? '1.3' : '1.4.6'}&key=9bfe3d8b8882b7d3e4c23e43d38b18ba`;
            if(this.getIosVersion()) {
                script1.src = `https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba`;
            }else {
                script1.src = `https://webapi.amap.com/maps?v=1.4.6&key=9bfe3d8b8882b7d3e4c23e43d38b18ba`;
            }
			amapBox.insertAdjacentElement("beforeend", script1);
			document.body.appendChild(amapBox);
        },
        //初始化地图
        initMap(){
            var that = this;
            var addParams = this.$route.query;
			var adderssArr = [];
            var map = new AMap.Map('allmap', {
				resizeEnable: true,
				zoom: 15,
				center: [108.383765, 22.813923],
				scrollWheel : true
            });
            var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
			var tenTimer;
            function pursue() {
                map.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
                //给一个定位过程的loading
                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, //是否使用高精度定位，默认:true
                        timeout: 10000, //超过10秒后停止定位，默认：无穷大
                        maximumAge: 0, //定位结果缓存0毫秒，默认：0
                        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                        showButton: true, //显示定位按钮，默认：true
                        buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
                        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
                    });
                    var placeSearch = new AMap.PlaceSearch({
                        pageSize: 10,
                        pageIndex: 1,
                        map: map,
                        autoFitView : true
                    });
                    if(!JSON.parse(localStorage.getItem("locateIn")) && !JSON.parse(localStorage.getItem("locateOut"))){
                        that.locateSpot = [{"address":"定位中..."}];
                        tenTimer = setTimeout(() => {
                            that.locateSpot = [{"address":"定位失败"}];
                        },11000)
                        map.addControl(geolocation);
                        geolocation.getCurrentPosition();
                        //添加定位失败和定位成功的监听事件
                        geolocation.on("complete", function (result) {
                            console.log('定位成功')
                            tenTimer = null;
                            let lists = [];
                            let obj = {};
                            let Pos = {};
                            if(result.addressComponent) {
                                result.formateAdd = result.addressComponent.city + result.addressComponent.district + result.addressComponent.street + result.addressComponent.streetNumber;
                            }
                            lists.push(result);
                            that.locateSpot = lists;
                            lists.forEach((item,index) => {
                                that.polygonList.forEach((element,indent) => {
                                    let lnglat = new AMap.LngLat(item.position.lng, item.position.lat);
                                    element.contains(lnglat) ? item.inArea = true : '';
                                },this)
                            },this)
                            that.searchCity = result.addressComponent.city || result.addressComponent.province;
                            // console.log(that.searchCity,"searchCity");
                            if(result.inArea && result.addressComponent){
                                obj.province = result.addressComponent.province;
                                obj.city = result.addressComponent.city || '市辖区';
                                obj.region = result.addressComponent.district;
                                obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                                obj.positionlng = result.position.lng;
                                obj.positionlat = result.position.lat;
                                obj.addressid = "-1";
                                Pos.province = result.addressComponent.province;
                                Pos.city = result.addressComponent.city || '市辖区';
                                Pos.region = result.addressComponent.district;
                                Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                                Pos.positionlng = result.position.lng;
                                Pos.positionlat = result.position.lat;
                                Pos.addressid = "-1";
                                Pos.inArea = true;
                                localStorage.setItem("locateIn", JSON.stringify(obj));
                                localStorage.setItem("currentPos", JSON.stringify(Pos));
                                !that.locationInfo && that.$store.dispatch('qxz/updateLocation', obj);
                            }else if(!result.inArea && result.addressComponent){
                                obj.address = '不在配送范围内';
                                obj.province = result.addressComponent.province;
                                obj.city = result.addressComponent.city;
                                obj.formateAdd = result.formattedAddress;
                                obj.positionlng = result.position.lng;
                                obj.positionlat = result.position.lat;
                                Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                                Pos.province = result.addressComponent.province;
                                Pos.city = result.addressComponent.city;
                                Pos.formateAdd = result.formattedAddress;
                                Pos.positionlng = result.position.lng;
                                Pos.positionlat = result.position.lat;
                                Pos.inArea = false;
                                localStorage.setItem("locateOut", JSON.stringify(obj));
                                localStorage.setItem("currentPos", JSON.stringify(Pos));
                                that.$store.dispatch('qxz/updateScopeOut', obj);
                            }
                            localStorage.setItem('poslng', result.position.lng);
                            localStorage.setItem('poslat', result.position.lat);
                            
                            // console.log(result.position.lng,result.position.lat,"存贮");
                            let cpoint = [];
                            cpoint.push(result.position.lng);
                            cpoint.push(result.position.lat);
                            var maxNearPoi = 3;
                            placeSearch.searchNearBy("",cpoint,200,function(status,res){
                                let nearPoint = res.poiList.pois;
                                nearPoint.length > 3 ? nearPoint.length = 3 : "";
                                nearPoint && nearPoint.forEach((item,index) => {
                                    that.polygonList.forEach((element,indent) => {
                                        let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                                        element.contains(lnglat) ? item.inArea = true : "";
                                    },this)
                                },this)
                                that.vicintyList = nearPoint;
                            })
                        });
                        geolocation.on("error", function () {
                            console.log('定位失败')
                            that.locateSpot = [{"address":"定位失败"}];
                        });
                    }else{
                        let cpoint = [];
                        localStorage.getItem('locateIn') && that.$store.dispatch('qxz/updateLocation', JSON.parse(localStorage.getItem('locateIn')));
                        localStorage.getItem('locateOut') && that.$store.dispatch('qxz/updateScopeOut', JSON.parse(localStorage.getItem('locateOut')));
                        localStorage.getItem('currentPos') ? that.searchCity = JSON.parse(localStorage.getItem('currentPos')).city || JSON.parse(localStorage.getItem('currentPos')).province : "";

                        let poslng = JSON.parse(localStorage.getItem('currentPos')).positionlng;
                        let poslat = JSON.parse(localStorage.getItem('currentPos')).positionlat;

                        // console.log("正常")
                        if(localStorage.getItem('currentPos')){
                            cpoint.push(poslng);
                            cpoint.push(poslat);
                        }
                        var maxNearPoi = 3;
                        // console.log(cpoint,"cpoint")
                        placeSearch.searchNearBy("",cpoint,200,function(status,res){
                            // console.log(status,res,"!!!!!!!!!!!!!!!");
                            let nearPoint = res.poiList.pois;
                            nearPoint.length > 3 ? nearPoint.length = 3 : "";
                            nearPoint && nearPoint.forEach((item,index) => {
                                that.polygonList.forEach((element,indent) => {
                                    let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                                    element.contains(lnglat) ? item.inArea = true : "";
                                },this)
                            },this)
                            that.vicintyList = nearPoint;
                        })
                    } 
                });
            }
            (function () {
				var isShow = false;
				//请求配送范围的经纬度数组
				// let url = "http://172.19.5.89:33004/address/getTMS";
                let url = api.customer_host + "/address/getTMS";
                if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
                }
				axios.get(url,{
						"longitudeandlatitude":""
					})
					.then(function (res) {
						that.polygonList = [];
						//门店配送范围
						let array = new Array();
						for(let item of res.data.data[0]){
							let Arr = new Array();
							for(let it of JSON.parse(item.longitudeandlatitude)){
								let arr = new Array();
								arr[0] = it.a;
								arr[1] = it.b;
								Arr.push(arr);
							}
							item.deptid == localStorage.getItem("storeId") && array.push(Arr);
						}
						//多边形覆盖物节点坐标数组
						for (let item of array){
							var polygon = new AMap.Polygon({
								map: map,
								path: item,//设置多边形边界路径
								strokeColor: "red", //线颜色
								strokeOpacity: 0.2, //线透明度
								strokeWeight: 3,    //线宽
								fillColor: "red", //填充色
								fillOpacity: 0.35//填充透明度
							});
							polygon.setMap(map);
							that.polygonList.push(polygon);
						}
						// console.log(that.polygonList,"polygonList");
                        pursue();
					})
					.catch(function (res) {
						//console.log(res);
					});
			})();
        },
        //重新定位
        relocate(){
            // console.log("init");
            var that = this;
            this.locateSpot = [{"address":"定位中..."}];
            var addParams = this.$route.query;
			var adderssArr = [];
            var map = new AMap.Map('allmap', {
				resizeEnable: true,
				zoom: 15,
				center: [108.383765, 22.813923],
				scrollWheel : true
            });
            var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
			var tenTimer;
            map.plugin(['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
				//给一个定位过程的loading
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 10000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
				});

				map.addControl(geolocation);
				// setTimeout(function () {
				geolocation.getCurrentPosition();
				// }, 5000);
				tenTimer = setTimeout(() => {
                    that.locateSpot = [{"address":"定位失败"}];
                },11000)
				//添加定位失败和定位成功的监听事件
				geolocation.on("complete", function (result) {
                    //清除计时器
                    clearTimeout(tenTimer);
                    let lists = [];
                    let obj = {};
                    let Pos = {};
                    if(result.addressComponent) {
                        result.formateAdd = result.addressComponent.city + result.addressComponent.district + result.addressComponent.street + result.addressComponent.streetNumber;
                    }
                    lists.push(result);
                    that.locateSpot = lists;
                    lists.forEach((item,index) => {
                        that.polygonList.forEach((element,indent) => {
                            let lnglat = new AMap.LngLat(item.position.lng, item.position.lat);
                            element.contains(lnglat) ? item.inArea = true : item.inArea = false;
                        },this)
                    },this)
                    that.searchCity = result.addressComponent.city || result.addressComponent.province;
                    // console.log(that.searchCity,"searchCity");
                    if(result.inArea && result.addressComponent){
                        obj.province = result.addressComponent.province;
                        obj.city = result.addressComponent.city || '市辖区';
                        obj.region = result.addressComponent.district;
                        obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                        obj.positionlng = result.position.lng;
                        obj.positionlat = result.position.lat;
                        obj.addressid = "-1";
                        Pos.province = result.addressComponent.province;
                        Pos.city = result.addressComponent.city || '市辖区';
                        Pos.region = result.addressComponent.district;
                        Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                        Pos.positionlng = result.position.lng;
                        Pos.positionlat = result.position.lat;
                        Pos.addressid = "-1";
                        Pos.inArea = true;
                        localStorage.setItem("locateIn", JSON.stringify(obj));
                        localStorage.setItem("currentPos", JSON.stringify(Pos));
                        !that.locationInfo && that.$store.dispatch('qxz/updateLocation', obj);
                    }else if(!result.inArea && result.addressComponent){
                        obj.address = '不在配送范围内';
                        obj.province = result.addressComponent.province;
                        obj.city = result.addressComponent.city;
                        obj.formateAdd = result.formattedAddress;
                        obj.positionlng = result.position.lng;
                        obj.positionlat = result.position.lat;
                        Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                        Pos.province = result.addressComponent.province;
                        Pos.city = result.addressComponent.city;
                        Pos.formateAdd = result.formattedAddress;
                        Pos.positionlng = result.position.lng;
                        Pos.positionlat = result.position.lat;
                        Pos.inArea = false;
                        localStorage.setItem("locateOut", JSON.stringify(obj));
                        localStorage.setItem("currentPos", JSON.stringify(Pos));
                        that.$store.dispatch('qxz/updateScopeOut', obj);
                    }

                    localStorage.setItem('poslng', result.position.lng);
                    localStorage.setItem('poslat', result.position.lat);
                    
                    var auto = new AMap.Autocomplete ({
                        city: that.searchCity,
                        // input: 'search-input'
                    });

                    let cpoint = [];
                    cpoint.push(result.position.lng);
                    cpoint.push(result.position.lat);
                    var maxNearPoi = 3;
                    placeSearch.searchNearBy("",cpoint,200,function(status,res){
                        let nearPoint = res.poiList.pois;
                        nearPoint.length > 3 ? nearPoint.length = 3 : "";
                        nearPoint && nearPoint.forEach((item,index) => {
                            that.polygonList.forEach((element,indent) => {
                                let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                                element.contains(lnglat) ? item.inArea = true : "";
                            },this)
                        },this)
                        that.vicintyList = nearPoint;
                    })
				});
				geolocation.on("error", function () {
                    that.locateSpot = [{"address":"定位失败"}];
                });

				var placeSearch = new AMap.PlaceSearch({
					pageSize: 10,
					pageIndex: 1,
					map: map,
					autoFitView : true
				});
				placeSearch.on("complete", function (e) {
                    console.log(e,"搜索成功");
                });
            });
            (function () {
				var isShow = false;
				//请求配送范围的经纬度数组
				// let url = "http://172.19.5.89:33004/address/getTMS";
                let url = api.customer_host + "/address/getTMS";
                if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
                }
				axios.get(url,{
						"longitudeandlatitude":""
					})
					.then(function (res) {
						that.polygonList = [];
						//门店配送范围
						let array = new Array();
						for(let item of res.data.data[0]){
							let Arr = new Array();
							for(let it of JSON.parse(item.longitudeandlatitude)){
								let arr = new Array();
								arr[0] = it.a;
								arr[1] = it.b;
								Arr.push(arr);
							}
							item.deptid == localStorage.getItem("storeId") && array.push(Arr);
						}
						//多边形覆盖物节点坐标数组
						for (let item of array){
							var polygon = new AMap.Polygon({
								map: map,
								path: item,//设置多边形边界路径
								strokeColor: "red", //线颜色
								strokeOpacity: 0.2, //线透明度
								strokeWeight: 3,    //线宽
								fillColor: "red", //填充色
								fillOpacity: 0.35//填充透明度
							});
							polygon.setMap(map);
							that.polygonList.push(polygon);
						}
						// console.log(that.polygonList,"polygonList")
					})
					.catch(function (res) {
						//console.log(res);
					});
			})();
        },
        //前往地图页面
        ToMap(){
            this.$router.push("map");
        },
        //搜索地址
        searchEvent(){
            // console.log(this.searchCity,'当前城市');
            let searchCity = this.searchCity;
            var auto = new AMap.Autocomplete ({
                city: searchCity,
                // city: "上海",
                // input: 'search-input'
            });
            let autocomplete = new AMap.Autocomplete(auto);
            autocomplete.search(this.keyword, (status, e) => {
                //TODO:开发者使用result自己进行下拉列表的显示与交互功能
                let assumeListUL = this.$refs.assumeListUL;
                let assumeList = this.$refs.assumeList;
                assumeList.style.maxHeight = this.clientHeight - 120 + "px";
                let Arr = new Array();
                let priorityList = new Array();
                let restList = new Array();
                e.tips && e.tips.forEach((item,index) => {
                    item.location && item.location.lng && Arr.push(item);
                },this)
                Arr.length && Arr.forEach((item,index) => {
                    this.polygonList.forEach((element,indent) => {
                        let lnglat = new AMap.LngLat(item.location.lng, item.location.lat);
                        element.contains(lnglat) ? item.inArea = true : "";
                    },this)
                },this)
                Arr.forEach(item => {
                    item.inArea ? priorityList.push(item) : restList.push(item);
                })
                let TerminalList = priorityList.concat(restList);
                this.positionList = TerminalList || [];
            });
        }
    },
    watch:{
        // locationInfo(newVal){
        //     if(newVal){
        //         // console.log(newVal,"locationInfo")
        //         let storeCode = newVal.storeCode;
        //         this.storeList.forEach((item,index) => {
        //             if(storeCode == item.storeCode){
        //                 localStorage.setItem("storeCode", storeCode);
        //                 localStorage.setItem("storeId", item.storeId);
        //                 localStorage.setItem("storeName", item.storeName);
        //                 localStorage.setItem("storeLng", item.positionLng);
        //                 localStorage.setItem("storeLat", item.positionLat);
        //                 window.api.storeCode = storeCode;
        //                 localStorage.setItem("locateIn", JSON.stringify(newVal));
        //                 this.$store.dispatch('cjy/storeCodeOnChange');
        //             }
        //         },this)
        //     }
        // },
        keyword(){
            this.searchEvent();
        }
    }
}
</script>
<style scoped>
#perChoose{
    width: 100%;
    height: 100%;
    overflow: auto;
}
.searcher{
    width: 100%;
    height: 2.2rem;
    background: white;
    box-sizing: border-box;
    padding-top: .3rem;
}
.location{
    width: 100%;
    height: 1.8rem;
    background: #FFFBD9;
    color: #7FB65F;
    line-height: 1.8rem;
    text-align: left;
    box-sizing: border-box;
    padding-left: .5rem;
}
.deliveryAdd{
    width: 100%;
    height: 1.8rem;
    line-height: 1.8rem;
    text-align: left;
    text-indent: .8rem;
    color: #A3A3A3;
    border-top: 1px solid #EDEDED;
    border-bottom: 1px solid #EDEDED;
}
.amap-sug-result{
    display: none !important;
}
.location{
    display: flex;
    align-items: center;
}
.vicinty{
    background: white;
}
.assumeList{
    position: absolute;
    z-index: 2;
    left: 0;
    top: 5.2rem;
    width: 100%;
    overflow: hidden;
}
.assumeList ul{
    width: 100%;
}
.assumeList ul li{
    width: 100%;
    box-sizing: border-box;
    padding: 0 .7rem;
    height: 2.4rem;
    border-bottom: 1px solid #eaeaea;
    text-align: left;
    background: white;
}
.assumeList ul li p{
    width: 95%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.locateSpot{
    width: 100%;
    height: 1.8rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: .2rem .7rem;
}
.nearlySpot{
    height: 1.8rem;
    text-align: left
}
.nearlySpot p{
    width: 100%;
    height: 100%;
    color: black;
    line-height: 1.8rem;
    border-bottom: 1px solid #ccc;
    text-indent: .7rem;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.firstItem{
    border-top: 1px solid #ccc;
}
.moreLocation{
    width: 100%;
    height: 1.8rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 .7rem;
}
.deliveryAddress{
    display: inline-block;
    color: #8EBE6D;
    width: 90%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>